# from my_py_toolkit.file.file_toolkit import *
import json
from tqdm import tqdm
import uuid

def readjson(file_path):
  """"""
  # make_path_legal(file_path)
  with open(file_path, "r", encoding="utf-8") as f:
    return json.load(f)
  
def write_file(text, path):
    # make_path_legal(path)
    with open(path, 'w', encoding='utf-8') as w:
        w.write(text)    

def get_uuid():
    return uuid.uuid1().hex

# 2 label 格式转换
# label studio
"""
<View>
   <Relations>
    <Relation value="org:founded"/>
  </Relations>
  <Labels name="label" toName="text">
    <Label value="Organization" background="orange"/>
    <Label value="Person" background="green"/>
    <Label value="Datetime" background="blue"/>
  </Labels>

  <Text name="text" value="$text"/>
</View>
"""

# uie
"""
[
  {
    "id": 40999,
    "text": "主诉_症状名称",
    "prefixKey": null,
    "suffixKey": null,
    "backgroundColor": "#73D8FF",
    "textColor": "#ffffff"
  }
]
"""
def handle_label(labels):
    result = []
    for label in labels:
        name = label['text']
        color = label['backgroundColor']
        cur =  f'    <Label value="{name}" background="{color}"/>'
        result.append(cur)
    result = '\n'.join(result)

    template = f"""<View>
   <Relations>
    <Relation value="org:founded"/>
  </Relations>
  <Labels name="label" toName="text">
{result}
  </Labels>

  <Text name="text" value="$text"/>
</View>
"""
    return template


def handle_ner_res(ner_ress):
    entities = []
    relations = []
    for ner_res in ner_ress:
      for name, values in ner_res.items():
          for item in values:
              cur_id = get_uuid()
              text = item['text']
              start = item['start']
              end = item['end']
              pro = item['probability']
              cur = {
                "id": cur_id,
                "from_name": "label",
                "to_name": "text",
                "type": "labels",
                "value": {
                  "start": start,
                  "end": end,
                  "score": pro,
                  "text": text,
                  "labels": [
                    name
                  ]
                }
            }
              entities.append(cur)

              for rel_name, rels in item['relations'].items():
                  for rel in rels:
                    sub_id = get_uuid()
                    sub = {
                        "id": sub_id,
                        "from_name": "label",
                        "to_name": "text",
                        "type": "labels",
                        "value": {
                          "start": rel['start'],
                          "end": rel['end'],
                          "score": rel['probability'],
                          "text": rel['text'],
                          "labels": [
                            rel_name
                          ]
                        }
                    }
                    entities.append(sub)

                    new_rel = {
                      "from_id": cur_id,
                      "to_id": sub_id,
                      "type": "relation",
                      "direction": "right"
                      }
                    relations.append(new_rel)
  
    pred = entities + relations

    result = [{
          "model_version": "one",
          "score": 0.5,
          "result": pred
          }
          ]
    return result


if __name__ == '__main__':
  # 1 doccanno 标签转 label studio 标签
  config = readjson(r'H:\work\文档\西医CDSS\病历结构化\主诉\西医CDSS_主诉_label_config.json')
  label_2 = handle_label(config)
  write_file(label_2, './res/test_label.txt')

  # 2 uie 模型输出结果转 label studio  格式
  # 1 标注结果格式转换
  data = [
        {
          "主诉_症状名称": [
            {
              "text": "胸闷",
              "start": 2,
              "end": 4,
              "probability": 0.9999004626038754,
              "relations": {
                "总病程": [
                  {
                    "text": "21年",
                    "start": 4,
                    "end": 7,
                    "probability": 0.9998170219708413
                  }
                ],
                "本次发病时长": [
                  {
                    "text": "1周",
                    "start": 10,
                    "end": 12,
                    "probability": 0.9963925291709792
                  }
                ]
              }
            }
          ],
          "主诉_伴随症状_名称": [
            {
              "text": "头疼",
              "start": 14,
              "end": 16,
              "probability": 0.9997292303050429,
              "relations": {
                "时长": [
                  {
                    "text": "2月",
                    "start": 16,
                    "end": 18,
                    "probability": 0.9982545220413428
                  }
                ]
              }
            }
          ]
        }
      ]
  """
  # 实体
  {
              "id": "abc",
              "from_name": "label",
              "to_name": "text",
              "type": "labels",
              "value": {
                "start": 29,
                "end": 31,
                "score": 0.70,
                "text": "27",
                "labels": [
                  "Date"
                ]
              }
            }

  # 关系
  {
            "from_id": "c5XsscPU-f",
            "to_id": "qjUaNy3vAg",
            "type": "relation",
            "direction": "right"
          }
  """
  handle_ner_res(data)
